package com.zw.april14thh.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.zw.april14thh.entity.AdminUser;
import com.zw.april14thh.service.AdminUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public class CUstomRealm extends AuthorizingRealm {

    @Autowired
    AdminUserService adminUserService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo();
        return authInfo;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println(authenticationToken);

        String username = (String)authenticationToken.getPrincipal();
        if (username == null || "".equals(username)) {
            throw new AuthenticationException("用户名不能为空");
        }

        AdminUser userFromDB = getUserFromDB(username);
        if (userFromDB==null){
            throw new AuthenticationException("查不到此用户");
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                userFromDB, userFromDB.getPassword()
                , ByteSource.Util.bytes(userFromDB.getSalt())
                , this.getName());


        return simpleAuthenticationInfo;
    }


    private AdminUser getUserFromDB(String username){
        AdminUser one = adminUserService.getOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getUserName, username));
        return one;
    }


}
